package middleware

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	"project/study-go/logger"
)

func AccessLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// Process request
		c.Next()

		param := gin.LogFormatterParams{
			Request: c.Request,
			Keys:    c.Keys,
		}

		// Stop timer
		param.TimeStamp = time.Now()
		param.Latency = param.TimeStamp.Sub(start)

		param.ClientIP = c.ClientIP()
		param.Method = c.Request.Method
		param.StatusCode = c.Writer.Status()
		param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()

		param.BodySize = c.Writer.Size()

		if raw != "" {
			path = path + "?" + raw
		}

		param.Path = path

		if param.StatusCode >= 500 {
			logger.AccessLogger.Errorf("| %3d | %13v | %15s | %-7s  %#v",
				param.StatusCode,
				param.Latency,
				param.ClientIP,
				param.Method,
				param.Path)
		} else if param.StatusCode == http.StatusOK {
			logger.AccessLogger.Infof("| %3d | %13v | %15s | %-7s  %#v",
				param.StatusCode,
				param.Latency,
				param.ClientIP,
				param.Method,
				param.Path)
		} else {
			logger.AccessLogger.Warnf("| %3d | %13v | %15s | %-7s  %#v",
				param.StatusCode,
				param.Latency,
				param.ClientIP,
				param.Method,
				param.Path)
		}
	}
}
